package uploader

import (
	"bbs-go/internal/pkg/config"
	"mime"
	"strings"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/mlogclub/simple/common/dates"
	"github.com/mlogclub/simple/common/digests"
	"github.com/mlogclub/simple/common/strs"
)

// generateKey 生成图片Key
func generateImageKey(data []byte, contentType string) string {
	md5 := digests.MD5Bytes(data)
	ext := ""
	if strs.IsNotBlank(contentType) {
		exts, err := mime.ExtensionsByType(contentType)
		if err == nil || len(exts) > 0 {
			ext = exts[0]
		}
	}
	if config.Instance.IsProd() {
		return "images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
	} else {
		// return "test/images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
		return "images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
	}
}

// func generateChatImageKey(data []byte, contentType string) string {
// 	md5 := digests.MD5Bytes(data)
// 	ext := ""
// 	if strs.IsNotBlank(contentType) {
// 		exts, err := mime.ExtensionsByType(contentType)
// 		if err == nil || len(exts) > 0 {
// 			ext = exts[0]
// 		}
// 	}
// 	if config.Instance.IsProd() {
// 		return "chat-images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
// 	} else {
// 		// return "test/images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
// 		return "chat-images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
// 	}
// }

func generateTagImageKey(tag string, data []byte, contentType string) string {
	md5 := digests.MD5Bytes(data)
	ext := ""
	if strs.IsNotBlank(contentType) {
		exts, err := mime.ExtensionsByType(contentType)
		if err == nil || len(exts) > 0 {
			ext = exts[0]
		}
	}
	if config.Instance.IsProd() {
		return "images/" + tag + "/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
	} else {
		// return "test/images/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
		return "images/" + tag + "/" + dates.Format(time.Now(), "2006/01/02/") + md5 + ext
	}
}

func download(url string) ([]byte, string, error) {
	rsp, err := resty.New().R().Get(url)
	if err != nil {
		return nil, "", err
	}
	return rsp.Body(), rsp.Header().Get("Content-Type"), nil
}

func GenerateFileKey(fileName string) string {
	date := dates.Format(time.Now(), "2006-01-02 15:04:05")
	md5 := digests.MD5Bytes([]byte(fileName + date))
	ext := GetFileExt(fileName)
	if config.Instance.IsProd() {
		return "resources/" + dates.Format(time.Now(), "2006/01/02/") + md5 + "." + ext
	} else {
		return "resources/" + dates.Format(time.Now(), "2006/01/02/") + md5 + "." + ext
	}
}

func GetFileExt(filename string) string {
	// 使用strings.LastIndexByte查找文件名中最后一个'.'的位置
	dotIndex := strings.LastIndexByte(filename, '.')
	// 如果'.'不存在或者它是文件名中的第一个字符（即文件名以'.'开始），则返回空字符串
	if dotIndex == -1 || dotIndex == 0 {
		return ""
	}
	// 返回'.'之后的所有字符作为扩展名
	return filename[dotIndex+1:]
}
